#include <iostream>
#include <sys/types.h>     
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <string>
#include <unistd.h>
#include <string.h>


void Usage(std::string proc)
{
    std::cout<<"\n\rUsage: "<<proc<<" serverip serverport\n"<<std::endl;
}


//   ./tcpclient serverip  serverport
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    //1.创建socket
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        std::cout<<"client socket fail!"<<std::endl;
        return 1;
    }
    std::cout<<"client socket successfully!"<<std::endl;

    sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());

    //Tcp客户端需要bind吗?
    //需要,但是不需要显示绑定,由os自己随机绑定
    //UDP第一次发送数据的时候bind, TCP第一次发起连接的时候bind
    //2.connnet
    int n=connect(sockfd,(sockaddr*)&server,sizeof(server));
    if(n<0)
    {
        std::cout<<"client connect fail!"<<std::endl;
        return 2;
    }
    std::cout<<"client connect successfully!"<<std::endl;

    //3.发送消息
    std::string message;
    while(true)
    {
        //发送消息
        std::cout<<"Please Enter# ";
        std::getline(std::cin,message);
        write(sockfd,message.c_str(),message.size());


        //接受返回消息
        char inbuffer[4096];
        int n = read(sockfd,inbuffer,sizeof(inbuffer));
        if(n>0)
        {
            inbuffer[n]=0;
            std::cout<<inbuffer<<std::endl;
        }
 
    }

   







    close(sockfd);
    return 0;
}